package com.sihai.ehr.web.action.leave;

import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.core.utils.DateUtils;
import com.sihai.ehr.model.biz.LeaveOfficeProject;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.*;
import com.sihai.ehr.web.action.EHRAction;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * author: wxn
 * @since 13-4-27 20:10
 * 离职分析管理Action
 */
@Results({
        @Result(name = "add", location = "leave_project_input.jsp"),
        @Result(name = "list", location = "leave_project_list.jsp"),
        @Result(name = "main", location = "leave_office_analysis_main.jsp")
})
public class LeaveOfficeAnalysisAction extends EHRAction {
    @BeanInject
    private LeaveOfficeApplyService leaveOfficeApplyService;
    @BeanInject
    private EmployeeService employeeService;
    @BeanInject
    private UserService userService;
    @BeanInject
    private OrganizationService organizationService;

    private LeaveOfficeProject project;

    private List<Organization> organizations;

    private int startYear;
    private int endYear;

    //"year":year, "month":month, "orgId":orgId, "dutyId":dutyId, "edu":edu, "sex":sex, "reason":reason, "organizationId":"${organizationId}"
    private int year;
    private int month;
    private Long orgId;
    private Long dutyId;
    private String edu;
    private String sex;
    private String reason;

    private List<Object[]> reason_chart_data;
    private List[] sex_chart_data;
    private List<Object[]> number_rank_data;
    private List<Object[]> ratio_rank_data;

    //离职分析管理
    @Action("/leave/analysis-main")
    public String main() throws Exception {
        organizations = organizationService.findChildren(null, true, null, null);
        if (organizationId == null && organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        Calendar c = Calendar.getInstance();
        startYear = c.get(Calendar.YEAR) - 20;
        endYear = c.get(Calendar.YEAR);
        year = endYear;
        month = c.get(Calendar.MONTH)+1;
        return "main";
    }


    private Long searchOrgId;
    private void init(){
        searchOrgId = organizationId;
        if(orgId != null && orgId > 0){
            searchOrgId = orgId;
        }
        if(dutyId != null && dutyId <= 0){
            dutyId = null;
        }
        if(StringUtils.equals(edu, "-1")){
            edu = null;
        }
        if(StringUtils.equals(sex, "-1")){
            sex = null;
        }
    }

    //查找离职原因饼图数据
    @Action(value = "/analysis-reason-chart", results = {@Result(name = "success", type = "json", params = {"root", "reason_chart_data"})})
    public String findReason() throws Exception {
        init();
        reason_chart_data = leaveOfficeApplyService.findForReasonChart(searchOrgId, dutyId, edu, sex, year, month);

        return SUCCESS;
    }

    //查找最近5个月离职男女分析图数据
    @Action(value = "/analysis-last-five-monty-chart", results = {@Result(name = "success", type = "json", params = {"root", "sex_chart_data"})})
    public String findLast() throws Exception {
        init();

        List<Object[]> list = leaveOfficeApplyService.findForSexChart(searchOrgId, dutyId, edu, reason, year, month);

        Map<String, Long> map = new HashMap<String, Long>();
        if(list != null && !list.isEmpty()){
            for(Object[] data : list){ //data={1,0,2013,4}
                map.put(String.format("%s-%s-%s", (Integer)data[2], (Integer)data[3], (String)data[1]), (Long)data[0]); //key:2013-2-0, value:20
            }
        }
        List<String> dateList = new ArrayList<String>(5);
        List<Long> manCountList = new ArrayList<Long>(5);
        List<Long> womanCountList = new ArrayList<Long>(5);
        for(int i=0; i<5; i++){
            int yy = year;
            int mm = 0;
            if(month - i <= 0){
                yy = year-1;
                mm = 12 + (month-i);
            }else{
                mm = month-i;
            }
            dateList.add(String.format("'%s年%s月'", yy, mm));
            if(list != null && !list.isEmpty()){
                //查找指定年-月的男离职数
                String menKey = String.format("%s-%s-0", yy, mm);
                if(map.containsKey(menKey)){
                    manCountList.add(map.get(menKey));
                }else{
                    manCountList.add(0L);
                }
                //查找指定年-月的女离职数
                String womenKey = String.format("%s-%s-1", yy, mm);
                if(map.containsKey(womenKey)){
                    womanCountList.add(map.get(womenKey));
                }else{
                    womanCountList.add(0L);
                }
            }else{
                manCountList.add(0L);
                womanCountList.add(0L);
            }
        }

        sex_chart_data = new List[]{dateList, manCountList, womanCountList};

        return SUCCESS;
    }

    //查找离职人数排行榜数据
    @Action(value = "/analysis-number-rank", results = {@Result(name = "success", type = "json", params = {"root", "number_rank_data"})})
    public String findNumberRank() throws Exception {
        init();
        Limit limit = new Limit(0, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        //c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month-1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date currentDate = c.getTime();//当前天
        System.out.println("wxn------当前天-"+sdf.format(currentDate));
        List<Object[]> listCurrentDate = leaveOfficeApplyService.findForNumberRank(searchOrgId, dutyId, edu, sex, reason, currentDate, limit);
        c.add(Calendar.DATE, 0 - c.get(Calendar.DAY_OF_WEEK) + 1);
        Date currentWeekDate = c.getTime();//当前星期
        System.out.println("wxn------当前星期-"+sdf.format(currentWeekDate));
        List<Object[]> listCurrentWeekDate = leaveOfficeApplyService.findForNumberRank(searchOrgId, dutyId, edu, sex, reason, currentWeekDate, limit);
        c.set(Calendar.DATE, 1);
        Date currentMonthDate = c.getTime();//当前月
        System.out.println("wxn------当前月-"+sdf.format(currentMonthDate));
        List<Object[]> listCurrentMonthDate = leaveOfficeApplyService.findForNumberRank(searchOrgId, dutyId, edu, sex, reason, currentMonthDate, limit);
        if(month <4){
            c.set(Calendar.MONTH, 0);
        }else if(month < 7){
            c.set(Calendar.MONTH, 3);
        }else if(month < 10){
            c.set(Calendar.MONTH, 6);
        }else{
            c.set(Calendar.MONTH, 9);
        }
        Date currentSeasonDate = c.getTime();//当前季
        System.out.println("wxn------当前季-"+sdf.format(currentSeasonDate));
        List<Object[]> listCurrentSeasonDate = leaveOfficeApplyService.findForNumberRank(searchOrgId, dutyId, edu, sex, reason, currentSeasonDate, limit);
        c.set(Calendar.MONTH, 0);
        Date currentYearDate = c.getTime();//当前年
        System.out.println("wxn------当前年-"+sdf.format(currentYearDate));
        List<Object[]> listCurrentYearDate = leaveOfficeApplyService.findForNumberRank(searchOrgId, dutyId, edu, sex, reason, currentYearDate, limit);
        number_rank_data = new ArrayList<Object[]>(5);
        add(listCurrentDate);
        add(listCurrentWeekDate);
        add(listCurrentMonthDate);
        add(listCurrentSeasonDate);
        add(listCurrentYearDate);
        return SUCCESS;
    }

    private void add(List<Object[]> list){
        if(list != null && list.size() > 0){
            number_rank_data.add(list.get(0));
        }else{
            number_rank_data.add(new Object[]{0, "无人员离职"});
        }
    }

    //查找离职比率排行榜数据
    @Action(value = "/analysis-ratio-rank", results = {@Result(name = "success", type = "json", params = {"root", "ratio_rank_data"})})
    public String findRatioRank() throws Exception {
        init();

        ratio_rank_data = leaveOfficeApplyService.findForRatioRank(searchOrgId, dutyId, edu, sex, reason, year, month);

        return SUCCESS;
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public LeaveOfficeProject getProject() {
        return project;
    }

    public void setProject(LeaveOfficeProject project) {
        this.project = project;
    }

    public int getStartYear() {
        return startYear;
    }

    public int getEndYear() {
        return endYear;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public void setOrgId(Long orgId) {
        this.orgId = orgId;
    }

    public void setDutyId(Long dutyId) {
        this.dutyId = dutyId;
    }

    public void setEdu(String edu) {
        this.edu = edu;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public String getReason() {
        return reason;
    }

    public List<Object[]> getReason_chart_data() {
        return reason_chart_data;
    }

    public List[] getSex_chart_data() {
        return sex_chart_data;
    }

    public List<Object[]> getNumber_rank_data() {
        return number_rank_data;
    }

    public List<Object[]> getRatio_rank_data() {
        return ratio_rank_data;
    }
}
